package com.appheader.rongmaphone.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.appheader.rongmaphone.R;
import com.appheader.rongmaphone.activity.LoginActivity;
import com.appheader.rongmaphone.activity.SuggestActivity;
import com.appheader.rongmaphone.cache.CacheManager;
import com.appheader.rongmaphone.cache.preference.PreferenceUtil;
import com.appheader.rongmaphone.constants.GlobalVars;
import com.appheader.rongmaphone.utils.ActivityManager;
import com.appheader.rongmaphone.utils.DataCleanManager;
import com.appheader.rongmaphone.utils.network.HttpUtil;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserSetFragment extends Fragment implements View.OnClickListener {
    private ImageView imageView;
    private RelativeLayout clearData;
    private RelativeLayout suggestBack;
    private TextView showCacheData;
    private TextView userLogout;
    private String path = "";
    private PreferenceUtil preferenceUtil;
    private static final int TAKE_PICTURE = 0x000000;

    public UserSetFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_user_set, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        //退出登录时删除公共目录
        preferenceUtil = new PreferenceUtil(getActivity(),PreferenceUtil.PUB);
        path = Environment.getExternalStorageDirectory() + File.separator + "camera.jpg";
        try {
            //显示cache缓存的大小
            showCacheData.setText(DataCleanManager.getCacheSize(new File(GlobalVars.getAppFilesDir() + File.separator + "cache")));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void initView(View view) {
        imageView = (ImageView) view.findViewById(R.id.user_img);
        clearData = (RelativeLayout) view.findViewById(R.id.clear_data);
        suggestBack = (RelativeLayout) view.findViewById(R.id.suggestions_layout);
        showCacheData = (TextView) view.findViewById(R.id.show_cache_data);
        userLogout = (TextView) view.findViewById(R.id.user_logout);

    }

    //
//    public String  photo() {
//        File file = new File(Environment.getExternalStorageDirectory(),
//                "myimage");
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        path = CameraUtils.takePhoto(getActivity(),
//                file.getAbsolutePath(),
//                String.valueOf(System.currentTimeMillis()) + ".jpg",
//                TAKE_PICTURE);
//        System.out.println("路径：" + path);
//        return path;
//    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setClickListener();
    }

    private void setClickListener() {
//        imageView.setOnClickListener(this);
        clearData.setOnClickListener(this);
        suggestBack.setOnClickListener(this);
        userLogout.setOnClickListener(this);

    }

    //截取图片
//    public void cropImage(Uri uri, int outputX, int outputY, int requestCode) {
//        //裁剪图片意图
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        intent.putExtra("crop", "true");
//        //裁剪框的比例，1：1是个圆形的，如果是2:1是个矩形的
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        //裁剪后输出图片的尺寸大小
//        intent.putExtra("outputX", outputX);
//        intent.putExtra("outputY", outputY);
//        //图片格式
//        intent.putExtra("outputFormat", "JPEG");
//        intent.putExtra("noFaceDetection", true);
//        intent.putExtra("return-data", true);
//        startActivityForResult(intent, requestCode);
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.user_img://头像
//                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//                builder.setTitle("选择方式");
//                builder.setItems(new String[]{"从手机本地", "拍照"}, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        switch (which) {
//                            case 0:
//                                Intent intentBendi = new Intent(Intent.ACTION_PICK);
//                                //设置获取图片的uri和类型
//                                intentBendi.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                                startActivityForResult(intentBendi, 1);
//                                break;
//                            case 1:
//                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                //保存在一个额外路径
//                                intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(path)));
//                                startActivityForResult(intent, 0);
////                                photo();
//                                break;
//                        }
//                    }
//                });
//
//                builder.show();
//                break;
            case R.id.clear_data://清除缓存
                AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
                builder1.setMessage("确定要删除缓存吗");
                builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                //在这里做清除缓存的动作
                builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

//                        List<String> list = DbUtil.selectUpLoadPic();
//                        for (int i = 0; i < list.size(); i++) {
//                            File file = new File(list.get(i));
//                            if (file.exists() && file.isFile()) {
//                                file.delete();
//                            }
//                        }
                        CacheManager.getPublicDataCache().clearPubData();
                        try {
                            showCacheData.setText(DataCleanManager.getCacheSize(new File(GlobalVars.getAppFilesDir() + File.separator + "cache")));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                builder1.show();
                break;
            case R.id.suggestions_layout://意见反馈
                final Intent intent = new Intent(getActivity(), SuggestActivity.class);
                startActivity(intent);
                break;
            case R.id.user_logout://用户退出登录

                AlertDialog.Builder logoutBuilder = new AlertDialog.Builder(getActivity());
                logoutBuilder.setMessage("确定要退出吗");
                logoutBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                //在这里做
                logoutBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //清楚当前应用
//                        CurrentUserManager.clearCurrentUser();
                        //清楚所有保存在 SharedPreferences中用户个人信息
                        HttpUtil.getUserLogOutOkHttpClient(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }
                            @Override
                            public void onResponse(Call call, Response response) throws IOException {

                                String string = response.body().string();
                                Log.e("TAG", "onResponse: " + string);
                            }
                        });
                        preferenceUtil.clear();
                        //退出所有的activity
                        ActivityManager.getInstance().popAllActivity();
                        Intent intent1 = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent1);
                    }
                });
                logoutBuilder.show();
                break;
        }
    }


//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0 && resultCode == getActivity().RESULT_OK) {
////            Uri uri = data.getData();
////            cropImage(uri, 100, 100, 3);
//            cropImage(Uri.fromFile(new File(path)), 100, 100, 3);
//        } else if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {
//            Uri picUri = data.getData();
//            cropImage(picUri, 100, 100, 3);
//        } else if (requestCode == 3 && resultCode == getActivity().RESULT_OK) {
//            Uri data1 = data.getData();
//            if (data1 == null) {
//                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
//                if (bitmap != null) {
//                    imageView.setImageBitmap(bitmap);
//                }
//            } else {
//                Bitmap bitmap = BitmapFactory.decodeFile(data1.toString());
//                if (bitmap != null) {
//                    imageView.setImageBitmap(bitmap);
//                }
//            }
//        }
//    }
}
